package com.zzx.service.impl;

import java.util.TreeMap;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.base.MPJBaseMapper;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.zzx.common.core.text.Convert;
import com.zzx.entity.TGx;
import com.zzx.entity.TProductGx;
import com.zzx.entity.TProductGxGroup;
import com.zzx.mapper.TProductGxGroupMapper;
import com.zzx.service.TProductGxGroupService;
import com.zzx.service.TProductGxService;
import com.zzx.utils.EntityUtils;
import com.zzx.utils.PageUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zzx
 * @description 针对表【t_product_gx_group(产品工序分组表)】的数据库操作Service实现
 * @createDate 2025-06-14
 */
@Service
public class TProductGxGroupServiceImpl extends ServiceImpl<TProductGxGroupMapper, TProductGxGroup>
        implements TProductGxGroupService {

    @Resource
    private TProductGxService tProductGxService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(TProductGxGroup param) {

        if (ObjectUtils.isEmpty(param.getProductGxGroupId())) {
            param.setProductGxGroupId(IdUtil.getSnowflakeNextId());
        } else {
            TProductGxGroup dbEntity = this.getBaseMapper().selectById(param.getProductGxGroupId());
            if (dbEntity != null) {
                EntityUtils.mergeNonNullProperties(dbEntity, param);
            }
        }
        this.saveOrUpdate(param);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteById(TProductGxGroup param) {
        tProductGxService.remove(new LambdaQueryWrapper<TProductGx>().eq(TProductGx::getProductGxGroupId, param.getProductGxGroupId()));
        this.removeById(param.getProductGxGroupId());
    }

    @Override
    public List<TProductGxGroup> selectBy(TProductGxGroup param) {
        MPJLambdaWrapper<TProductGxGroup> wrappers = new MPJLambdaWrapper<TProductGxGroup>();
        wrappers.selectAll(TProductGxGroup.class);
        wrappers.select(TGx::getGxName, TGx::getGxCode);
        wrappers.select(TProductGx::getUnitPrice, TProductGx::getNum);
        wrappers.select(TProductGx::getProductGxId);
        wrappers.select(TProductGx::getGxId);
        wrappers.selectAs(TProductGx::getSort, TProductGxGroup::getSubSort);
        wrappers.selectAs(TProductGx::getMark, TProductGxGroup::getMark);

        wrappers.leftJoin(TProductGx.class, TProductGx::getProductGxGroupId, TProductGxGroup::getProductGxGroupId);
        wrappers.leftJoin(TGx.class, TGx::getGxId, TProductGx::getGxId);
        wrappers.eq(TProductGxGroup::getProductId, param.getProductId());
        // 多租户拦截器会自动添加 company_id 条件
        wrappers.orderByAsc(TProductGxGroup::getSort);
        wrappers.orderByAsc(TProductGx::getSort);

        //执行
//        IPage<TProductGxGroup> page = this.getBaseMapper().selectJoinPage(PageUtils.createMPJPage(param.getPageNum(), param.getPageSize()), TProductGxGroup.class, wrappers);

        List<TProductGxGroup> tProductGxGroups = this.getBaseMapper().selectList(wrappers);


        // 根据 sort 升序排列
//        List<TProductGxGroup> sortedList = tProductGxGroups.stream()
//                .sorted(Comparator.comparingInt(TProductGxGroup::getSort)) // 按照 sort 升序排列
//                .collect(Collectors.toList());

        // 分组操作
        Map<String, List<TProductGxGroup>> groupedResult = tProductGxGroups.stream()
                .collect(Collectors.groupingBy(
                        item -> item.getSort() + ":" + item.getProductGxGroupId() + ":" + item.getProductGxGroupCode() + ":" + item.getProductGxGroupName(),
                        TreeMap::new, // 使用 TreeMap 实现按键排序
                        Collectors.mapping(item -> item, Collectors.toList())
                ));


        List<TProductGxGroup> result = new ArrayList<>();
        for (Map.Entry<String, List<TProductGxGroup>> entry : groupedResult.entrySet()) {
            TProductGxGroup group = new TProductGxGroup();

            String[] keyArr = entry.getKey().split(":");
            group.setProductGxGroupId(Convert.toLong(keyArr[1]));
            group.setProductGxGroupCode(keyArr[2]);
            group.setProductGxGroupName(keyArr[3]);

            List<TProductGxGroup> items = entry.getValue();
            // 提取每个分组中的 TProductGx 数据
            List<TProductGx> tProductGxs = new ArrayList<>();
            for (TProductGxGroup item : items) {
                if (ObjectUtils.isEmpty(item.getProductGxId())) {
                    continue;
                }
                TProductGx productGx = new TProductGx();
                productGx.setProductGxId(item.getProductGxId());
                productGx.setGxId(item.getGxId());
                productGx.setNum(item.getNum());
                productGx.setUnitPrice(item.getUnitPrice());
                productGx.setSort(item.getSubSort());
                productGx.setGxCode(item.getGxCode());
                productGx.setGxName(item.getGxName());
                productGx.setMark(item.getMark());
                tProductGxs.add(productGx);
            }

            tProductGxs.sort(Comparator.comparingInt(TProductGx::getSort));

            // 设置封装好的子数据
            if (!ObjectUtils.isEmpty(tProductGxs)) {
                group.setTProductGxs(tProductGxs);
            }
            // 可以将 group 添加到最终返回的列表中
            result.add(group);
        }

        return result;

//        LambdaQueryWrapper<TProductGxGroup> wrapper = new LambdaQueryWrapper<>(TProductGxGroup.class);
//
//        if (!ObjectUtils.isEmpty(param.getProductGxGroupName())) {
//            wrapper.like(TProductGxGroup::getProductGxGroupName, param.getProductGxGroupName());
//        }
//        if (!ObjectUtils.isEmpty(param.getProductGxGroupCode())) {
//            wrapper.like(TProductGxGroup::getProductGxGroupCode, param.getProductGxGroupCode());
//        }
//        if (!ObjectUtils.isEmpty(param.getProductGxGroupId())) {
//            wrapper.eq(TProductGxGroup::getProductGxGroupId, param.getProductGxGroupId());
//        }
//
//        wrapper.eq(TProductGxGroup::getCompanyId, UserContext.getCompanyId());
//        wrapper.orderByAsc(TProductGxGroup::getSort);
//
//        return this.getBaseMapper().selectPage(
//                PageUtils.createPage(param.getPageNum(), param.getPageSize()),
//                wrapper
//        );
    }

    @Override
    public TProductGxGroup findById(String id) {
        return this.getBaseMapper().selectById(id);
    }
}
